-- SPDX-License-Identifier: GPL-3.0-or-later

local extension = Package("ling7")
extension.extensionName = "lingling"

local U = require "packages/utility/utility"

local zhaokuangyin = General(extension, "lingling__zhaokuangyin", "song", 4)
local zhihengz = fk.CreateActiveSkill{
  name = "lingling__zhihengz",
  anim_type = "drawcard",
  card_num = 0,
  target_num = 0,
  prompt = "#lingling__zhihengz",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    player:drawCards(1, self.name)
    if player.dead then return end
    local cards = room:askForDiscard(player, 1, 999, true, self.name, false, nil, "#lingling__zhihengz-discard", true)
    if #cards == 0 then return end
    local yes1, yes2
    for _, id in ipairs(cards) do
      local card = Fk:getCardById(id)
      if card.trueName == "slash" then
        yes1 = true
      elseif card.type == Card.TypeTrick then
        yes2 = true
      end
    end
    room:throwCard(cards, self.name, player, player)
    if player.dead then return end
    room:drawCards(player, #cards + (yes1 and yes2 and 1 or 0), self.name)
    if player.dead then return end
    if (yes1 or yes2) and not (yes1 and yes2) then
      if yes1 then
        room:addPlayerMark(player, "lingling__zhihengz_trick", 1)
      else
        room:addPlayerMark(player, "lingling__zhihengz_slash", 1)
      end
    end
  end
}
local zhihengz_delay = fk.CreateTriggerSkill{
  name = "#lingling__zhihengz_delay",
  mute = true,
  events = {fk.DrawNCards},
  can_trigger = function(self, event, target, player, data)
    return target == player and data.n > 0 and
      player:getMark("lingling__zhihengz_slash") + player:getMark("lingling__zhihengz_trick") > 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local cards = {}
    if player:getMark("lingling__zhihengz_slash") > 0 then
      room:setPlayerMark(player, "lingling__zhihengz_slash", 0)
      local cards2 = room:getCardsFromPileByRule("slash")
      if #cards2 > 0 then
        table.insertTableIfNeed(cards, cards2)
      end
    end
    if player:getMark("lingling__zhihengz_trick") > 0 then
      room:setPlayerMark(player, "lingling__zhihengz_trick", 0)
      local cards2 = room:getCardsFromPileByRule(".|.|.|.|.|trick")
      if #cards2 > 0 then
        table.insertTableIfNeed(cards, cards2)
      end
    end
    if #cards > 0 then
      local n = math.min(#cards, data.n)
      data.n = data.n - n
      if room.logic:trigger(fk.BeforeDrawCard, player, {
        who = player,
        num = num,
        skillName = "phase_draw",
      }) then return end
      room:moveCardTo(cards, Card.PlayerHand, player, fk.ReasonDraw, "phase_draw", nil, false, player.id)
    end
  end,
}
local shiquan = fk.CreateActiveSkill{
  name = "lingling__shiquan",
  anim_type = "control",
  frequency = Skill.Limited,
  card_num = 0,
  target_num = 1,
  prompt = "#lingling__shiquan",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function (self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id and not Fk:currentRoom():getPlayerById(to_select):isKongcheng()
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local n = target:getHandcardNum()
    room:moveCardTo(target:getCardIds("h"), Card.PlayerHand, player, fk.ReasonPrey, self.name, nil, false, player.id)
    if player.dead or target.dead or player:isNude() then return end
    local cards = room:askForCard(player, n, n, true, self.name, false, nil, "#lingling__shiquan-give::"..target.id..":"..n)
    room:moveCardTo(cards, Card.PlayerHand, target, fk.ReasonGive, self.name, nil, false, player.id)
  end
}
zhihengz:addRelatedSkill(zhihengz_delay)
zhaokuangyin:addSkill(zhihengz)
zhaokuangyin:addSkill(shiquan)
Fk:loadTranslationTable{
  ["lingling__zhaokuangyin"] = "赵匡胤",
  ["#lingling__zhaokuangyin"] = "神武独断",
  ["illustrator:lingling__zhaokuangyin"] = "珊瑚虫",
  ["designer:lingling__zhaokuangyin"] = "伶",

  ["lingling__zhihengz"] = "制衡",
  [":lingling__zhihengz"] = "出牌阶段限一次，你可以摸一张牌，弃置任意张牌，然后摸等量的牌，若弃置牌中有【杀】也有锦囊牌，你额外摸一张牌，"..
  "若只有其中一种，你下个摸牌阶段必定能摸到另一种。",
  ["lingling__shiquan"] = "释权",
  [":lingling__shiquan"] = "限定技，出牌阶段，你可以获得一名其他角色所有手牌，然后交给其等量的牌。"..
  "<br><br> <font color = '#a40000'>太祖用心，尧舜之心也。",
  ["#lingling__zhihengz"] = "制衡：你可以摸一张牌，弃置任意张牌，然后摸等量的牌",
  ["#lingling__zhihengz-discard"] = "制衡：弃置任意张牌，摸等量的牌，根据其中有无【杀】和锦囊牌获得额外效果",
  ["#lingling__zhihengz_delay"] = "制衡",
  ["#lingling__shiquan"] = "释权：获得一名其他角色所有手牌，交给其等量的牌",
  ["#lingling__shiquan-give"] = "释权：请交给 %dest %arg张牌",
}

local zhaopu = General(extension, "lingling__zhaopu", "song", 3)
local zhifa = fk.CreateActiveSkill{
  name = "lingling__zhifa",
  anim_type = "drawcard",
  card_num = 1,
  min_target_num = 0,
  max_target_num = 1,
  prompt = "#lingling__zhifa",
  times = function(self)
    return Self.phase == Player.Play and 2 - Self:usedSkillTimes(self.name, Player.HistoryPhase) or -1
  end,
  can_use = function (self, player, card, extra_data)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) < 2
  end,
  card_filter = function(self, to_select, selected, targets)
    return #selected == 0 and Fk:getCardById(to_select).type == Card.TypeTrick
  end,
  target_filter = function(self, to_select, selected, selected_cards)
    return #selected == 0 and to_select ~= Self.id
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    if #effect.tos > 0 then
      local target = room:getPlayerById(effect.tos[1])
      room:moveCardTo(effect.cards, Card.PlayerHand, target, fk.ReasonGive, self.name, nil, true, player.id)
    else
      room:recastCard(effect.cards, player, self.name)
    end
    if not player.dead then
      player:drawCards(2, self.name)
    end
  end,
}
local shenbei = fk.CreateTriggerSkill{
  name = "lingling__shenbei",
  anim_type = "drawcard",
  events = {fk.EnterDying},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local to = room:askForChoosePlayers(player, table.map(room.alive_players, Util.IdMapper), 1, 1,
      "#lingling__shenbei-choose", self.name, true)
    if #to > 0 then
      self.cost_data = {tos = to}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data.tos[1])
    local cards = room:getCardsFromPileByRule(".|.|.|.|.|trick", 2, "allPiles")
    if #cards > 0 then
      room:moveCardTo(cards, Card.PlayerHand, to, fk.ReasonJustMove, self.name, nil, true, player.id)
    end
  end,
}
zhaopu:addSkill(zhifa)
zhaopu:addSkill(shenbei)
Fk:loadTranslationTable{
  ["lingling__zhaopu"] = "赵普",
  ["#lingling__zhaopu"] = "兴王开运",
  ["illustrator:lingling__zhaopu"] = "珊瑚虫",
  ["designer:lingling__zhaopu"] = "伶",

  ["lingling__zhifa"] = "制法",
  [":lingling__zhifa"] = "出牌阶段限两次，你可以将一张锦囊牌交给一名其他角色或重铸，然后摸两张牌。",
  ["lingling__shenbei"] = "神碑",
  [":lingling__shenbei"] = "你濒死时，你可以令一名角色随机从牌堆和弃牌堆获得两张锦囊牌。"..
  "<br><br> <font color = '#a40000'>抑抑人杰，佐命之元。",
  ["#lingling__zhifa"] = "制法：选择一张锦囊牌，交给一名其他角色，或不选目标重铸之，然后你摸两张牌",
  ["#lingling__shenbei-choose"] = "神碑：你可以令一名角色随机获得两张锦囊牌",
}

local sushi = General(extension, "lingling__sushi", "song", 3)
local feici = fk.CreateTriggerSkill{
  name = "lingling__feici",
  anim_type = "special",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      (player.phase == Player.Draw or (player.phase < 8 and player:getMark("lingling__feici-turn") > 0))
  end,
  on_trigger = function (self, event, target, player, data)
    player.room:setPlayerMark(player, "lingling__feici-turn", 0)
    self:doCost(event, target, player, data)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local success, dat = room:askForUseActiveSkill(player, "lingling__feici_viewas",
      "#lingling__feici-invoke:::"..player:getMark("@lingling__feici_num"), true)
    if success and dat then
      self.cost_data = dat
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local card = Fk:cloneCard(self.cost_data.interaction)
    card:addSubcards(self.cost_data.cards)
    card.skillName = self.name
    if card.type == Card.TypeEquip then
      local equip = room:printCard(card.name, card.suit, card.number)
      room:moveCardTo(self.cost_data.cards, Card.Void, nil, fk.ReasonJustMove)
      room:setCardMark(equip, "__vitural_equip", card.subcards[1])
      card = equip
    end
    room:useCard{
      from = player.id,
      tos = table.map(self.cost_data.targets, function(id) return {id} end),
      card = card,
    }
    if not player.dead then
      if player:getMark("@lingling__feici_num") > 0 then
        local values = {}
        for key, _ in pairs(player:getMark(self.name)) do
          table.insert(values, tonumber(key))
        end
        local record = player:getMark("lingling__feici_record")
        table.removeOne(values, record)
        room:setPlayerMark(player, "lingling__feici_record", player:getMark("@lingling__feici_num"))
        room:setPlayerMark(player, "@lingling__feici_num", table.random(values))
      end
      if Fk:translate(card.trueName, "zh_CN"):len() == Fk:translate(Fk:getCardById(self.cost_data.cards[1]).trueName, "zh_CN"):len() then
        room:setPlayerMark(player, "lingling__feici-turn", 1)
      end
      if Fk:getCardById(self.cost_data.cards[1]).color == Card.Black then
        player:drawCards(1, self.name)
      end
    end
  end,

  refresh_events = {fk.BeforeCardsMove},
  can_refresh = function (self, event, target, player, data)
    return player.seat == 1
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    local mirror_moves = {}
    for _, move in ipairs(data) do
      if not table.contains({Card.Void, Card.Processing, Card.PlayerEquip}, move.toArea) then
        local move_info = {}
        local mirror_info = {}
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerEquip then
            local real_id = Fk:getCardById(info.cardId):getMark("__vitural_equip")
            if real_id ~= 0 then
              room:setCardMark(Fk:getCardById(info.cardId), "__vitural_equip", 0)
              table.insert(mirror_info, table.simpleClone(info))
              info.cardId = real_id
              info.fromArea = Card.Void
            end
          end
          table.insert(move_info, info)
        end
        move.moveInfo = move_info
        if #mirror_info > 0 then
          local destruct_move = table.simpleClone(move)
          destruct_move.to = nil
          destruct_move.toArea = Card.Void
          destruct_move.moveInfo = mirror_info
          destruct_move.moveMark = nil
          destruct_move.moveVisible = true
          table.insert(mirror_moves, destruct_move)
        end
      end
    end
    if #mirror_moves > 0 then
      table.insertTable(data, mirror_moves)
    end
  end,

  on_acquire = function (self, player, is_start)
    local room = player.room
    room:setPlayerMark(player, "@lingling__feici_num", 4)
    if player:getMark(self.name) == 0 then
      local names = {}
      for _, card in ipairs(Fk.cards) do
        if not table.contains(room.disabled_packs, card.package.name) and not card.is_derived and
          (card.type == Card.TypeBasic or card.type == Card.TypeEquip or card:isCommonTrick()) then
          local index = tostring(Fk:translate(card.trueName, "zh_CN"):len())
          names[index] = names[index] or {}
          table.insertIfNeed(names[index], card.name)
        end
      end
      room:setPlayerMark(player, self.name, names)
    end
  end,
}
local feici_viewas = fk.CreateViewAsSkill{
  name = "lingling__feici_viewas",
  interaction = function(self)
    local all_names = Self:getMark("lingling__feici")[tostring(Self:getMark("@lingling__feici_num"))]
    local names = U.getViewAsCardNames(Self, "lingling__feici", all_names)
    if #names > 0 then
      return U.CardNameBox { choices = names }
    end
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  view_as = function(self, cards)
    if #cards ~= 1 or not self.interaction.data then return end
    local c = Fk:cloneCard(self.interaction.data)
    c.skillName = "lingling__feici"
    c:addSubcard(cards[1])
    return c
  end,
}
local yisuo = fk.CreateTriggerSkill{
  name = "lingling__yisuo",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {fk.AfterCardsMove, fk.BeforeCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.AfterCardsMove and #player:getCardIds("ej") > 1 then
        for _, move in ipairs(data) do
          if move.to == player.id and (move.toArea == Card.PlayerEquip or move.toArea == Card.PlayerJudge) then
            for _, info in ipairs(move.moveInfo) do
              if table.contains(player:getCardIds("ej"), info.cardId) then
                return true
              end
            end
          end
        end
      elseif event == fk.BeforeCardsMove then
        for _, move in ipairs(data) do
          if move.from == player.id and move.toArea ~= Card.Void then
            for _, info in ipairs(move.moveInfo) do
              if info.fromArea == Card.PlayerEquip or info.fromArea == Card.PlayerJudge then
                return true
              end
            end
          end
        end
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local ids = {}
    if event == fk.AfterCardsMove then
      for _, move in ipairs(data) do
        if move.to == player.id and (move.toArea == Card.PlayerEquip or move.toArea == Card.PlayerJudge) then
          for _, info in ipairs(move.moveInfo) do
            if table.contains(player:getCardIds("ej"), info.cardId) then
              table.insertIfNeed(ids, info.cardId)
            end
          end
        end
        if #ids > 0 then
          room:throwCard(ids, self.name, player, player)
          if not player.dead then
            player:drawCards(1, self.name)
          end
        end
      end
    elseif event == fk.BeforeCardsMove then
      local mirror_moves = {}
      for _, move in ipairs(data) do
        if move.from == player.id and move.toArea ~= Card.Void then
          local move_info = {}
          local mirror_info = {}
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerEquip or info.fromArea == Card.PlayerJudge then
              table.insertIfNeed(ids, info.cardId)
              table.insert(mirror_info, table.simpleClone(info))
            else
              table.insert(move_info, info)
            end
            move.moveInfo = move_info
          end
          if #mirror_info > 0 then
            local new_move = table.simpleClone(move)
            new_move.to = nil
            new_move.toArea = Card.DiscardPile
            new_move.moveReason = fk.ReasonPutIntoDiscardPile
            new_move.moveInfo = mirror_info
            new_move.moveMark = nil
            new_move.moveVisible = true
            table.insert(mirror_moves, new_move)
          end
        end
      end
      if #mirror_moves > 0 then
        table.insertTable(data, mirror_moves)
      end
    end
  end,
}
Fk:addSkill(feici_viewas)
sushi:addSkill(feici)
sushi:addSkill(yisuo)
Fk:loadTranslationTable{
  ["lingling__sushi"] = "苏轼",
  ["#lingling__sushi"] = "风流大观",
  ["illustrator:lingling__sushi"] = "珊瑚虫",
  ["designer:lingling__sushi"] = "伶",

  ["lingling__feici"] = "飞词",
  [":lingling__feici"] = "摸牌阶段开始时，你可以将一张牌当任意四字牌名的牌使用（基本牌、装备牌、普通锦囊牌），然后将“四字”改为与前两次"..
  "不同的其他字数，若用黑色牌转化，你摸一张牌，若用同牌名字数的牌转化，本回合下个阶段开始时也可以发动。",
  ["lingling__yisuo"] = "一蓑",
  [":lingling__yisuo"] = "你场上置入牌后，若你场上的牌多于一张，你弃置置入的牌并摸一张牌。你场上失去牌时，改为置入弃牌堆。"..
  "<br><br> <font color = '#a40000'>莫听穿林打叶声，何妨吟啸且徐行。",
  ["lingling__feici_viewas"] = "飞词",
  ["#lingling__feici-invoke"] = "飞词：你可以将一张牌当任意%arg字牌名的牌使用",
  ["@lingling__feici_num"] = "飞词",
}

local fanzhongyan = General(extension, "lingling__fanzhongyan", "song", 3)
local mingsi = fk.CreateTriggerSkill{
  name = "lingling__mingsi",
  anim_type = "control",
  events = {fk.TurnEnd},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and target:inMyAttackRange(player)
  end,
  on_cost = function (self, event, target, player, data)
    local use = U.askForPlayCard(player.room, player, nil, nil, self.name, "#lingling__mingsi-use", {bypass_times = true}, true)
    if use then
      self.cost_data = use
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local use = self.cost_data
    use.extraUse = true
    local n = use.card.type == Card.TypeTrick and 2 or 1
    player:drawCards(n, self.name)
    room:useCard(use)
    if target.dead or player.dead then return end
    local yes = #room.logic:getEventsOfScope(GameEvent.UseCard, 1, function(e)
      local u = e.data[1]
      return u.from == target.id and u.card.trueName == use.card.trueName
    end, Player.HistoryTurn) == 0
    if yes then
      use = room:askForUseCard(target, self.name, "slash", "#lingling__mingsi-slash:"..player.id, true,
        {
          bypass_distances = true,
          bypass_times = true,
          must_targets = {player.id},
        })
      if use then
        use.extraUse = true
        room:useCard(use)
      end
    end
  end,
}
local youle = fk.CreateTriggerSkill{
  name = "lingling__youle",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseChanging, fk.DrawNCards},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if event == fk.EventPhaseChanging then
        return data.to == Player.Draw or data.to == Player.Discard
      elseif event == fk.DrawNCards then
        return 2 * #table.filter(player.room.alive_players, function (p)
          return p:isWounded()
        end) < #player.room.alive_players
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.EventPhaseChanging then
      if data.to == Player.Draw then
        data.to = Player.Discard
      elseif data.to == Player.Discard then
        data.to = Player.Draw
      end
    elseif event == fk.DrawNCards then
      data.n = data.n + 1
    end
  end,
}
fanzhongyan:addSkill(mingsi)
fanzhongyan:addSkill(youle)
Fk:loadTranslationTable{
  ["lingling__fanzhongyan"] = "范仲淹",
  ["#lingling__fanzhongyan"] = "一世之师",
  ["illustrator:lingling__fanzhongyan"] = "珊瑚虫",
  ["designer:lingling__fanzhongyan"] = "伶",

  ["lingling__mingsi"] = "鸣死",
  [":lingling__mingsi"] = "攻击范围内有你的其他角色回合结束时，你可以使用一张牌并摸一张牌（使用锦囊牌则摸两张），若与其本回合使用的牌名称皆不同，"..
  "则其可以对你使用一张【杀】。",
  ["lingling__youle"] = "忧乐",
  [":lingling__youle"] = "你交换摸牌阶段和弃牌阶段的顺序。若场上受伤角色数少于一半，则摸牌阶段你多摸一张牌。"..
  "<br><br> <font color = '#a40000'>为社稷之固者，莫知范仲淹。",
  ["#lingling__mingsi-use"] = "鸣死：你可以使用一张牌并摸一张牌，使用锦囊牌则摸两张",
  ["#lingling__mingsi-slash"] = "鸣死：是否对 %src 使用一张【杀】？",
}

local wanganshi = General(extension, "lingling__wanganshi", "song", 3)
local gexin = fk.CreateTriggerSkill{
  name = "lingling__gexin",
  anim_type = "control",
  events = {fk.AskForRetrial},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and not player:isNude()
  end,
  on_cost = function(self, event, target, player, data)
    local card = player.room:askForDiscard(player, 1, 1, true, self.name, true, nil,
      "#lingling__gexin-ask::"..target.id..":"..data.reason, true)
    if #card > 0 then
      self.cost_data = {cards = card}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:throwCard(self.cost_data.cards, self.name, player, player)
    if player.dead then return end
    local cards = room:getNCards(3)
    room:moveCardTo(cards, Card.Processing, nil, fk.ReasonJustMove, self.name, nil, true, player.id)
    if player.dead then
      U.clearRemainCards(room, cards)
      return
    end
    local card = U.askforChooseCardsAndChoice(player, cards, {"OK"}, self.name, "#lingling__gexin-retrial")
    table.removeOne(cards, card[1])
    room:retrial(Fk:getCardById(card[1]), player, data, self.name, false)
    if player.dead then
      U.clearRemainCards(room, cards)
      return
    end
    if #cards > 0 then
      card = U.askforChooseCardsAndChoice(player, cards, {"OK"}, self.name, "#lingling__gexin-prey")
      room:moveCardTo(card, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id)
    end
    U.clearRemainCards(room, cards)
  end,
}
local gongsi = fk.CreateTriggerSkill{
  name = "lingling__gongsi",
  anim_type = "support",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Judge and
      #player:getCardIds("j") == 0
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    for i = 1, 2, 1 do
      if player.dead then return end
      local judge = {
        who = target,
        reason = self.name,
        pattern = ".|.|spade,heart",
        skipDrop = true,
      }
      room:judge(judge)
      local to
      if judge.card.suit == Card.Heart then
        to = player
      elseif judge.card.suit == Card.Spade then
        to = room:getLord()
      end
      if to and not to.dead and room:getCardArea(judge.card) == Card.Processing then
        room:moveCardTo(judge.card, Card.PlayerHand, to, fk.ReasonJustMove, self.name, nil, true, player.id)
      end
      if room:getCardArea(judge.card) == Card.Processing then
        room:moveCardTo(judge.card, Card.DiscardPile, nil, fk.ReasonJudge)
      end
    end
  end,
}
wanganshi:addSkill(gexin)
wanganshi:addSkill(gongsi)
Fk:loadTranslationTable{
  ["lingling__wanganshi"] = "王安石",
  ["#lingling__wanganshi"] = "镇国之石",
  ["illustrator:lingling__wanganshi"] = "珊瑚虫",
  ["designer:lingling__wanganshi"] = "伶",

  ["lingling__gexin"] = "革新",
  [":lingling__gexin"] = "当一名角色的判定牌生效前，你可以弃置一张牌，然后亮出牌堆顶三张牌，用其中一张牌代替之，你从剩余牌中获得一张。",
  ["lingling__gongsi"] = "公私",
  [":lingling__gongsi"] = "判定阶段，若你判定区没有牌，你可以判定两次，你获得<font color='red'>♥</font>判定牌，主公获得♠判定牌。"..
  "<br><br> <font color = '#a40000'>上与介甫如一人，此乃天也。",
  ["#lingling__gexin-ask"] = "朝柄：%dest 进行“%arg”判定，是否弃置一张牌，从牌堆顶三张牌中选一张牌代替之？",
  ["#lingling__gexin-retrial"] = "革新：选择用来修改判定的牌",
  ["#lingling__gexin-prey"] = "革新：获得其中一张牌",
}

local xinqiji = General(extension, "lingling__xinqiji", "song", 3)
local shishou = fk.CreateTriggerSkill{
  name = "lingling__shishou",
  anim_type = "offensive",
  events = {fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      local room = player.room
      local phase_judge, phase_play, phase_discard = {}, {}, {}
      room.logic:getEventsOfScope(GameEvent.Phase, 1, function (e)
        if e.data[1] == player then
          if e.data[2] == Player.Judge then
            table.insert(phase_judge, {e.id, e.end_id})
          elseif e.data[2] == Player.Play then
            table.insert(phase_play, {e.id, e.end_id})
          elseif e.data[2] == Player.Discard then
            table.insert(phase_discard, {e.id, e.end_id})
          end
        end
      end, Player.HistoryTurn)
      local n = 0
      if #phase_judge > 0 then
        if #room.logic:getEventsOfScope(GameEvent.Judge, 1, function (e)
          if table.find(phase_judge, function (info)
            return e.id >= info[1] and e.id <= info[2]
          end) then
            local judge = e.data[1]
            return judge.who == player and Fk.all_card_types[judge.reason] ~= nil
          end
        end, Player.HistoryTurn) > 0 then
          n = n + 1
        end
      end
      if #phase_play > 0 then
        if #room.logic:getEventsOfScope(GameEvent.UseCard, 1, function (e)
          if table.find(phase_play, function (info)
            return e.id >= info[1] and e.id <= info[2]
          end) then
            local use = e.data[1]
            return use.from == player.id
          end
        end, Player.HistoryTurn) > 0 then
          n = n + 1
        end
      end
      if #phase_discard > 0 then
        if #room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function (e)
          if table.find(phase_discard, function (info)
            return e.id >= info[1] and e.id <= info[2]
          end) then
            for _, move in ipairs(e.data) do
              if move.from == player.id and move.moveReason == fk.ReasonDiscard then
                return true
              end
            end
          end
        end, Player.HistoryTurn) > 0 then
          n = n + 1
        end
      end
      if n > 0 then
        self.cost_data = {extra_data = n}
        return true
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local cards = table.filter(U.getUniversalCards(player.room, "t"), function (id)
      return not table.contains(player:getTableMark("lingling__shishou-turn"), Fk:getCardById(id).name)
    end)
    local use = U.askForUseRealCard(room, player, cards, nil, self.name, "#lingling__shishou-ask:::"..self.cost_data.extra_data,
      {expand_pile = cards}, true, true)
    if use then
      self.cost_data.use = use
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    self.cost_data.extra_data = self.cost_data.extra_data - 1
    local card = Fk:cloneCard(self.cost_data.use.card.name)
    card.skillName = self.name
    room:addTableMark(player, "lingling__shishou-turn", card.name)
    local use = {
      card = card,
      from = player.id,
      tos = self.cost_data.use.tos,
    }
    room:useCard(use)
    if not player.dead and self.cost_data.extra_data > 0 then
      self:doCost(event, target, player, data)
    end
  end,
}
local nanchouSkill = fk.CreateActiveSkill{
  name = "lingling__nanchou__indulgence_skill",
  prompt = "#indulgence_skill",
  can_use = Util.CanUse,
  mod_target_filter = function(self, to_select, selected, user, card, distance_limited)
    return user ~= to_select
  end,
  target_filter = function(self, to_select, selected, _, card, extra_data)
    if not Util.TargetFilter(self, to_select, selected, _, card, extra_data) then return end
    return #selected == 0 and self:modTargetFilter(to_select, selected, Self.id, card, true)
  end,
  target_num = 1,
  on_effect = function(self, room, effect)
    local to = room:getPlayerById(effect.to)
    local judge = {
      who = to,
      reason = "indulgence",
      pattern = ".|.|spade,club",
    }
    room:judge(judge)
    local result = judge.card
    if result.suit ~= Card.Heart and result.suit ~= Card.Diamond then
      to:skip(Player.Play)
    end
    self:onNullified(room, effect)
  end,
  on_nullified = function(self, room, effect)
    room:moveCards{
      ids = room:getSubcardsByRule(effect.card, { Card.Processing }),
      toArea = Card.DiscardPile,
      moveReason = fk.ReasonUse,
    }
  end,
}
nanchouSkill.cardSkill = true
Fk:addSkill(nanchouSkill)
local nanchou = fk.CreateTriggerSkill{
  name = "lingling__nanchou",

  refresh_events = {fk.PreCardEffect},
  can_refresh = function(self, event, target, player, data)
    return data.to == player.id and table.contains(data.card.skillNames, "lingling__nanchou")
  end,
  on_refresh = function(self, event, target, player, data)
    local card = data.card:clone()
    local c = table.simpleClone(data.card)
    for k, v in pairs(c) do
      card[k] = v
    end
    card.skill = nanchouSkill
    data.card = card
  end,

  on_acquire = function (self, player, is_start)
    local room = player.room
    for _, p in ipairs(room:getOtherPlayers(player)) do
      room:handleAddLoseSkills(p, "lingling__nanchou&", nil, false, true)
    end
  end,
  on_lose = function (self, player, is_death)
    local room = player.room
    if not table.find(room:getOtherPlayers(player), function (p)
      return p:hasSkill(self, true)
    end) then
      for _, p in ipairs(room:getOtherPlayers(player)) do
        room:handleAddLoseSkills(p, "-lingling__nanchou&", nil, false, true)
      end
    end
  end,
}
local nanchou_viewas = fk.CreateViewAsSkill{
  name = "lingling__nanchou&",
  anim_type = "control",
  prompt = "#lingling__nanchou&",
  card_filter = function (self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).suit == Card.Diamond
  end,
  view_as = function(self, cards)
    if #cards == 0 then return end
    local card = Fk:cloneCard("indulgence")
    card:addSubcard(cards[1])
    card.skillName = "lingling__nanchou"
    return card
  end,
  --[[after_use = function (self, player, use)
    local room = player.room
    for _, id in ipairs(TargetGroup:getRealTargets(use.tos)) do
      local p = room:getPlayerById(id)
      if p:isWounded() and not p.dead then
        room:recover{
          who = p,
          num = 1,
          recoverBy = player,
          skillName = "lingling__nanchou",
        }
      end
    end
  end,]]--
  enabled_at_response = function (self, player, response)
    return not response
  end,
}
local nanchou_prohibit = fk.CreateProhibitSkill{
  name = "#lingling__nanchou_prohibit",
  is_prohibited = function(self, from, to, card)
    return card and table.contains(card.skillNames, "lingling__nanchou") and not to:hasSkill(nanchou)
  end,
}
nanchou_viewas:addRelatedSkill(nanchou_prohibit)
Fk:addSkill(nanchou_viewas)
xinqiji:addSkill(shishou)
xinqiji:addSkill(nanchou)
Fk:loadTranslationTable{
  ["lingling__xinqiji"] = "辛弃疾",
  ["#lingling__xinqiji"] = "词中之龙",
  ["illustrator:lingling__xinqiji"] = "珊瑚虫",
  ["designer:lingling__xinqiji"] = "伶",

  ["lingling__shishou"] = "试手",
  [":lingling__shishou"] = "回合结束时，你可以依次视为使用X张牌名不同的普通锦囊牌，X为你本回合满足以下项的次数：判定阶段判定了牌，"..
  "出牌阶段使用了牌，弃牌阶段弃置了牌。",
  ["lingling__nanchou"] = "难酬",
  [":lingling__nanchou"] = "其他角色可以将<font color='red'>♦</font>牌当【乐不思蜀】对你使用，此【乐不思蜀】判定为"..
  "<font color='red'>♦</font>也无效。"..
  "<br><br> <font color = '#a40000'>醉里挑灯看剑，梦回吹角连营。",
  ["lingling__nanchou&"] = "难酬",
  [":lingling__nanchou&"] = "你可以将<font color='red'>♦</font>牌当【乐不思蜀】对辛弃疾使用，此【乐不思蜀】判定为"..
  "<font color='red'>♦</font>也无效。",
  ["#lingling__shishou-ask"] = "试手：是否视为使用锦囊牌？（还剩%arg张）",
  ["#lingling__nanchou&"] = "难酬：你可以将<font color='red'>♦</font>牌当【乐不思蜀】对辛弃疾使用",
}

local zongze = General(extension, "lingling__zongze", "song", 3)
local duhe = fk.CreateActiveSkill{
  name = "lingling__duhe",
  anim_type = "offensive",
  card_num = 1,
  target_num = 1,
  prompt = "#lingling__duhe",
  target_tip = function(self, to_select, selected, selected_cards, _, selectable)
    if not selectable then return end
    if Self:getLastAlive().id == to_select or Self:getNextAlive().id == to_select then
      return "lingling__duhe_tip_1"
    else
      return "lingling__duhe_tip_2"
    end
  end,
  can_use = function (self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = function (self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).trueName == "jink"
  end,
  target_filter = function(self, to_select, selected)
    if #selected == 0 then
      if Self:getLastAlive().id == to_select or Self:getNextAlive().id == to_select then
        return not Fk:currentRoom():getPlayerById(to_select):isNude()
      else
        return true
      end
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:recastCard(effect.cards, player, self.name)
    if target.dead then return end
    if player:getLastAlive() == target or player:getNextAlive() == target then
      if not player.dead and not target:isNude() and target ~= player then
        local card = room:askForCardChosen(player, target, "he", self.name, "#lingling__duhe-prey::"..target.id)
        room:moveCardTo(card, Card.PlayerHand, player, fk.ReasonPrey, self.name, nil, false, player.id)
      end
    else
      room:damage{
        from = player,
        to = target,
        damage = 1,
        skillName = self.name,
      }
    end
  end,
}
local shangyou = fk.CreateTriggerSkill{
  name = "lingling__shangyou",
  anim_type = "control",
  events = {fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and not player:isKongcheng() and #player:getTableMark(self.name) < 3
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local success, dat = room:askForUseActiveSkill(player, "lingling__shangyou_active", "#lingling__shangyou-invoke", true)
    if success and dat then
      self.cost_data = {cards = dat.cards, choice = dat.interaction}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:addTableMark(player, self.name, Util.PhaseStrMapper(self.cost_data.choice))
    room:recastCard(self.cost_data.cards, player, self.name)
    if player.dead then return end
    local to = player:getLastAlive(true)
    if to == player then return end
    room:swapSeat(player, to)
    if room:askForSkillInvoke(player, self.name, nil, "#lingling__shangyou-ask::"..to.id) then
      to:turnOver()
    end
    if self:triggerable(event, target, player, data) then
      self:doCost(event, target, player, data)
    end
  end,

  refresh_events = {fk.EventPhaseChanging},
  can_refresh = function(self, event, target, player, data)
    return target == player and table.contains(player:getTableMark(self.name), data.to)
  end,
  on_refresh = function(self, event, target, player, data)
    data.to = Player.Play
  end,
}
local shangyou_active = fk.CreateActiveSkill{
  name = "lingling__shangyou_active",
  card_num = 1,
  target_num = 0,
  interaction = function()
    local all_choices = {"phase_judge", "phase_draw", "phase_discard"}
    local choices = table.filter(all_choices, function (s)
      return not table.contains(Self:getTableMark("lingling__shangyou"), Util.PhaseStrMapper(s))
    end)
    return UI.ComboBox {choices = choices, all_choices = all_choices}
  end,
  card_filter = function (self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).trueName == "slash"
  end,
}
Fk:addSkill(shangyou_active)
zongze:addSkill(duhe)
zongze:addSkill(shangyou)
Fk:loadTranslationTable{
  ["lingling__zongze"] = "宗泽",
  ["#lingling__zongze"] = "日月争光",
  ["illustrator:lingling__zongze"] = "珊瑚虫",
  ["designer:lingling__zongze"] = "伶",

  ["lingling__duhe"] = "渡河",
  [":lingling__duhe"] = "出牌阶段限一次，你可以重铸一张【闪】，然后对一名与你不相邻的角色造成1点伤害，或获得一名与你相邻的角色一张牌。",
  ["lingling__shangyou"] = "上游",
  [":lingling__shangyou"] = "回合结束时，你可以执行任意次：重铸一张【杀】，将一个出牌阶段外的阶段（判定阶段、摸牌阶段、弃牌阶段）永久变为"..
  "出牌阶段，然后与上家交换位置，且你可以令其翻面。"..
  "<br><br> <font color = '#a40000'>谁人共挽天河水，尽洗中原犬虏腥。",
  ["#lingling__duhe"] = "渡河：重铸一张【闪】，对一名不相邻角色造成1点伤害，或获得一名相邻角色一张牌",
  ["lingling__duhe_tip_1"] = "获得牌",
  ["lingling__duhe_tip_2"] = "造成伤害",
  ["#lingling__duhe-prey"] = "渡河：获得 %dest 一张牌",
  ["lingling__shangyou_active"] = "上游",
  ["#lingling__shangyou-invoke"] = "上游：是否重铸一张【杀】，将一个阶段改为出牌阶段并与上家交换位置？",
  ["#lingling__shangyou-ask"] = "上游：是否令 %dest 翻面？",
}

local yuefei = General(extension, "lingling__yuefei", "song", 4)
local nufa = fk.CreateViewAsSkill{
  name = "lingling__nufa",
  anim_type = "offensive",
  pattern = ".|.|.|.|fire__slash,fire_attack,looting",
  prompt = "#lingling__nufa",
  interaction = function(self)
    local all_names = {"fire__slash", "fire_attack", "looting"}
    local names = U.getViewAsCardNames(Self, self.name, all_names)
    if #names > 0 then
      return U.CardNameBox { choices = names, all_choices = all_names }
    end
  end,
  card_filter = function(self, to_select, selected)
    return #selected < 2 and Fk:getCardById(to_select).color == Card.Red
  end,
  view_as = function(self, cards)
    if #cards ~= 2 then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    card:addSubcards(cards)
    return card
  end,
  enabled_at_response = function (self, player, response)
    return not response
  end,
}
local nufa_trigger = fk.CreateTriggerSkill{
  name = "#lingling__nufa_trigger",
  anim_type = "drawcard",
  main_skill = nufa,
  events = {fk.Damage},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(nufa) and data.card and data.card.color == Card.Red and player.phase == Player.Play and
      #player.room.logic:getActualDamageEvents(2, function (e)
        local damage = e.data[1]
        return damage.from == player and damage.card and damage.card.color == Card.Red
      end, Player.HistoryPhase) == 1
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:drawCards(1, "lingling__nufa")
    if not player.dead and #room.logic:getActualDamageEvents(2, function (e)
      local damage = e.data[1]
      return damage.from == player
    end, Player.HistoryTurn) == 1 then
      player:drawCards(2, "lingling__nufa")
    end
  end,
}
local guochou = fk.CreateTriggerSkill{
  name = "lingling__guochou",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.Damaged},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and (player.room:getLord() == target or target.seat == 1) and
    #player.room.logic:getActualDamageEvents(4, function (e)
      local damage = e.data[1]
      return damage.to == target
    end, Player.HistoryTurn) < 4
  end,
  on_use = function(self, event, target, player, data)
    player.room:addPlayerMark(player, "@lingling__guochou", 1)
  end,

  refresh_events = {fk.TurnStart, fk.EventPhaseChanging},
  can_refresh = function (self, event, target, player, data)
    if target == player then
      if event == fk.TurnStart then
        return player:getMark("@lingling__guochou") > 0
      elseif event == fk.EventPhaseChanging then
        if data.to == Player.Judge then
          return player:getMark("@lingling__guochou-turn") > 0
        elseif data.to == Player.Discard then
          return player:getMark("@lingling__guochou-turn") > 1
        elseif data.to == Player.Draw then
          return player:getMark("@lingling__guochou-turn") > 2
        end
      end
    end
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    if event == fk.TurnStart then
      room:setPlayerMark(player, "@lingling__guochou-turn", player:getMark("@lingling__guochou"))
      room:setPlayerMark(player, "@lingling__guochou", 0)
    elseif event == fk.EventPhaseChanging then
      data.to = Player.Play
    end
  end,
}
nufa:addRelatedSkill(nufa_trigger)
yuefei:addSkill(nufa)
yuefei:addSkill(guochou)
Fk:loadTranslationTable{
  ["lingling__yuefei"] = "岳飞",
  ["#lingling__yuefei"] = "精忠报国",
  ["illustrator:lingling__yuefei"] = "珊瑚虫",
  ["designer:lingling__yuefei"] = "伶",

  ["lingling__nufa"] = "怒发",
  [":lingling__nufa"] = "你可以将两张红色牌当火【杀】【火攻】或【趁火打劫】使用。你每个出牌阶段首次使用红色牌造成伤害后，你摸一张牌，"..
  "若为本回合首次，再摸两张牌。",
  ["lingling__guochou"] = "国仇",
  [":lingling__guochou"] = "主公每轮前三次受到伤害后，你依次将你下回合的判定阶段、弃牌阶段、摸牌阶段改为出牌阶段。"..
  "<br><br> <font color = '#a40000'>踏破贺兰山缺，君自有还我山河胆魄。",
  ["#lingling__nufa"] = "怒发：你可以将两张红色牌当火【杀】【火攻】或【趁火打劫】使用",
  ["#lingling__nufa_trigger"] = "怒发",
  ["@lingling__guochou"] = "国仇",
  ["@lingling__guochou-turn"] = "国仇",
}

local hanshizhong = General(extension, "lingling__hanshizhong", "song", 4)
local jinglv = fk.CreateTriggerSkill{
  name = "lingling__jinglv",
  anim_type = "offensive",
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and data.card.type == Card.TypeTrick and
      data.tos and not data.card.multiple_targets and
      not table.contains(player:getTableMark("lingling__jinglv_names-turn"), data.card.name) then
      local tos = TargetGroup:getRealTargets(data.tos)
      return #tos == 1 and tos[1] ~= player.id and not player.room:getPlayerById(tos[1]).dead
    end
  end,
  on_cost = function(self, event, target, player, data)
    local tos = TargetGroup:getRealTargets(data.tos)
    if player.room:askForSkillInvoke(player, self.name, nil, "#lingling__jinglv-invoke::"..tos[1]..":"..data.card.name) then
      self.cost_data = {tos = tos}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:addTableMark(player, "lingling__jinglv_names-turn", data.card.name)
    local to = room:getPlayerById(self.cost_data.tos[1])
    room:damage{
      from = player,
      to = to,
      damage = 1,
      skillName = self.name,
    }
    if not to.dead then
      local mark = to:getTableMark(self.name)
      local info = mark[string.format("%.0f", player.id)] or {}
      table.insertIfNeed(info, data.card.name)
      mark[string.format("%.0f", player.id)] = info
      room:setPlayerMark(to, self.name, mark)
    end
  end,

  refresh_events = {fk.TurnStart},
  can_refresh = function (self, event, target, player, data)
    return target == player and player:getMark(self.name) ~= 0
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "lingling__jinglv-turn", player:getMark(self.name))
    room:setPlayerMark(player, self.name, 0)
    room:handleAddLoseSkills(player, "lingling__jinglv&", nil, false, true)
    room.logic:getCurrentEvent():findParent(GameEvent.Turn, true):addCleaner(function()
      room:handleAddLoseSkills(player, "-lingling__jinglv&", nil, false, true)
    end)
  end,
}
local jinglv_viewas = fk.CreateViewAsSkill{
  name = "lingling__jinglv&",
  anim_type = "negative",
  prompt = "#lingling__jinglv&",
  interaction = function(self)
    local all_names = {}
    for _, names in pairs(Self:getMark("lingling__jinglv-turn")) do
      table.insertTable(all_names, names)
    end
    local names = U.getViewAsCardNames(Self, self.name, all_names)
    if #names > 0 then
      return U.CardNameBox { choices = names, all_choices = all_names }
    end
  end,
  card_filter = function (self, to_select, selected)
    return #selected == 0
  end,
  view_as = function(self, cards)
    if #cards == 0 or not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    card:addSubcard(cards[1])
    card.skillName = self.name
    return card
  end,
  before_use = function (self, player, use)
    local room = player.room
    local mark = player:getMark("lingling__jinglv-turn")
    local id = string.format("%.0f", TargetGroup:getRealTargets(use.tos)[1])
    for pId, names in pairs(mark) do
      if pId == id then
        for i = #names, 1, -1 do
          if names[i] == use.card.name then
            table.remove(mark[pId], i)
            break
          end
        end
      end
      if #mark[pId] == 0 then
        mark[pId] = nil
      end
    end
    if next(mark) then
      room:setPlayerMark(player, "lingling__jinglv-turn", mark)
    else
      room:setPlayerMark(player, "lingling__jinglv-turn", 0)
    end
  end,
  enabled_at_play = function(self, player)
    if player:getMark("lingling__jinglv-turn") == 0 then return end
    local mark = player:getMark("lingling__jinglv-turn")
    for _, p in ipairs(Fk:currentRoom().alive_players) do
      if mark[string.format("%.0f", p.id)] then
        return true
      end
    end
  end,
}
local jinglv_prohibit = fk.CreateProhibitSkill{  --FIXME: 目标多指！
  name = "#lingling__jinglv_prohibit",
  is_prohibited = function(self, from, to, card)
    if from:getMark("lingling__jinglv-turn") ~= 0 and card and table.contains(card.skillNames, "lingling__jinglv&") then
      for pId, names in pairs(from:getMark("lingling__jinglv-turn")) do
        if not (string.format("%.0f", to.id) == pId and table.contains(names, card.name)) then
          return true
        end
      end
    end
  end,
}
jinglv_viewas:addRelatedSkill(jinglv_prohibit)
Fk:addSkill(jinglv_viewas)
local yitun = fk.CreateTriggerSkill{
  name = "lingling__yitun",
  anim_type = "support",
  events = {fk.TargetConfirmed},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.type == Card.TypeTrick and data.from ~= player.id and
      not player:isKongcheng() and #player.room:getOtherPlayers(player) > 0
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local to, cards = room:askForChooseCardsAndPlayers(player, 1, 999, table.map(room:getOtherPlayers(player), Util.IdMapper), 1, 1,
      ".|.|.|hand", "#lingling__yitun-invoke", self.name, true, false)
    if #to > 0 and #cards > 0 then
      self.cost_data = {tos = to, cards = cards}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data.tos[1])
    room:moveCardTo(self.cost_data.cards, Card.PlayerHand, to, fk.ReasonGive, self.name, nil, false, player.id)
    if not to.dead then
      room:setPlayerMark(to, "@@lingling__yitun", 1)
    end
  end,

  refresh_events = {fk.TurnStart},
  can_refresh = function(self, event, target, player, data)
    return target == player and target:getMark("@@lingling__yitun") > 0
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "@@lingling__yitun", 0)
    room:setPlayerMark(player, "@@lingling__yitun-turn", 1)
    player:skip(Player.Discard)
  end,
}
hanshizhong:addSkill(jinglv)
hanshizhong:addSkill(yitun)
Fk:loadTranslationTable{
  ["lingling__hanshizhong"] = "韩世忠",
  ["#lingling__hanshizhong"] = "辅世良臣",
  ["illustrator:lingling__hanshizhong"] = "珊瑚虫",
  ["designer:lingling__hanshizhong"] = "伶",

  ["lingling__jinglv"] = "劲旅",
  [":lingling__jinglv"] = "当你对其他角色使用单体锦囊牌结算后，你可以对其造成1点伤害，其下回合出牌阶段可以将一张牌当该锦囊牌对你使用"..
  "（每回合每种牌名限一次）。",
  ["lingling__jinglv&"] = "劲旅",
  [":lingling__jinglv&"] = "出牌阶段，你可以将一张牌当记录的锦囊牌对韩世忠使用（每回合每种牌名限一次）。",
  ["lingling__yitun"] = "移屯",
  [":lingling__yitun"] = "当其他角色使用锦囊牌指定你为目标后，你可以将任意手牌交给一名其他角色，获得牌的角色跳过下回合的弃牌阶段。"..
  "<br><br> <font color = '#a40000'>忠贯日月，靡渝金石之坚。功若丘山，具焕旂常之纪。",
  ["#lingling__jinglv-invoke"] = "劲旅：是否对 %dest 造成1点伤害？其下回合出牌阶段可以将一张牌当【%arg】对你使用",
  ["#lingling__jinglv&"] = "劲旅：你可以将一张牌当记录的锦囊牌对韩世忠使用",
  ["#lingling__yitun-invoke"] = "移屯：你可以将任意手牌交给一名角色，其跳过下回合弃牌阶段",
  ["@@lingling__yitun"] = "跳过弃牌阶段",
  ["@@lingling__yitun-turn"] = "跳过弃牌阶段",
}

local diqing = General(extension, "lingling__diqing", "song", 4)
local zhaqiao = fk.CreateActiveSkill{
  name = "lingling__zhaqiao",
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  prompt = "#lingling__zhaqiao",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and (Self:getNextAlive().id == to_select or Self:getLastAlive().id == to_select)
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    if #room.draw_pile == 0 then return end
    local all_cards, cards = {}, {}
    for i = 1, math.min(3, #room.draw_pile), 1 do
      table.insert(all_cards, room.draw_pile[i])
    end
    local card = U.askforChooseCardsAndChoice(target, all_cards, {"OK"}, self.name, "#lingling__zhaqiao-discard", {"Cancel"})
    if #card > 0 then
      table.removeOne(all_cards, card[1])
      table.insert(cards, card[1])
      room:moveCardTo(card, Card.DiscardPile, nil, fk.ReasonDiscard, self.name, nil, true, target.id)
      if player.dead then return end
    end
    if #all_cards > 0 then
      card = U.askforChooseCardsAndChoice(player, all_cards, {"OK"}, self.name, "#lingling__zhaqiao-discard", {"Cancel"})
      if #card > 0 then
        table.insert(cards, card[1])
        room:moveCardTo(card, Card.DiscardPile, nil, fk.ReasonDiscard, self.name, nil, true, player.id)
      end
    end
    local ids = table.filter(cards, function (id)
      return Fk:getCardById(id).color == Card.Black
    end)
    if #ids == 2 and not target.dead then
      room:setPlayerMark(target, "@@lingling__zhaqiao", 1)
    elseif #ids == 1 and not player.dead and table.contains(room.discard_pile, ids[1]) then
      room:moveCardTo(ids, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id)
    end
  end,
}
local zhaqiao_delay = fk.CreateTriggerSkill{
  name = "#lingling__zhaqiao_delay",

  refresh_events = {fk.TurnStart},
  can_refresh = function(self, event, target, player, data)
    return target == player and target:getMark("@@lingling__zhaqiao") > 0
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "@@lingling__zhaqiao", 0)
    room:setPlayerMark(player, "@@lingling__zhaqiao-turn", 1)
    player:skip(Player.Play)
  end,
}
local yexi = fk.CreateTriggerSkill{
  name = "lingling__yexi",
  anim_type = "offensive",
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.trueName == "slash" and #AimGroup:getAllTargets(data.tos) == 1
  end,
  on_cost = function(self, event, target, player, data)
    if player.room:askForSkillInvoke(player, self.name, nil, "#lingling__yexi-invoke::"..data.to) then
      self.cost_data = {tos = {data.to}}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(data.to)
    local n = 0
    for i = 1, 3, 1 do
      local judge = {
        who = player,
        reason = self.name,
        pattern = ".|.|spade,club",
      }
      room:judge(judge)
      if judge.card.color == Card.Black then
        n = n + 1
      end
    end
    if n > 2 then
      data.additionalDamage = (data.additionalDamage or 0) + 1
    end
    if n > 1 then
      data.unoffsetableList = table.map(room.alive_players, Util.IdMapper)
    end
    if n > 0 then
      room:broadcastPlaySound("./packages/standard_cards/audio/card/qinggang_sword")
      room:setEmotion(player, "./packages/standard_cards/image/anim/qinggang_sword")
      local use_event = room.logic:getCurrentEvent():findParent(GameEvent.UseCard, true)
      if use_event == nil then return end
      room:addPlayerMark(to, fk.MarkArmorNullified)
      use_event:addCleaner(function()
        room:removePlayerMark(to, fk.MarkArmorNullified)
      end)
    end
  end,
}
zhaqiao:addRelatedSkill(zhaqiao_delay)
diqing:addSkill(zhaqiao)
diqing:addSkill(yexi)
Fk:loadTranslationTable{
  ["lingling__diqing"] = "狄青",
  ["#lingling__diqing"] = "面涅将军",
  ["illustrator:lingling__diqing"] = "珊瑚虫",
  ["designer:lingling__diqing"] = "伶",

  ["lingling__zhaqiao"] = "诈巧",
  [":lingling__zhaqiao"] = "出牌阶段限一次，你可以与一名邻家一起观看牌堆顶的三张牌，然后其可以弃置其中一张牌，你可以弃置其中一张牌，"..
  "若以此法弃置：两张黑色牌，其跳过下一个出牌阶段；一张黑色牌，你获得之。",
  ["lingling__yexi"] = "夜袭",
  [":lingling__yexi"] = "当你使用【杀】指定唯一目标后，你可以连续判定三次，每有一次为黑色，此【杀】便依次获得以下效果：无视防具、无法抵消、"..
  "造成的伤害+1。"..
  "<br><br> <font color = '#a40000'>天生狄公，辅圣推忠。情存义烈，志嫉顽凶。",
  ["#lingling__zhaqiao"] = "诈巧：与一名邻家观看牌堆顶三张牌并依次可以弃置其中一张牌，根据双方弃置黑色牌数执行效果",
  ["#lingling__zhaqiao-discard"] = "诈巧：你可以弃置其中一张牌",
  ["@@lingling__zhaqiao"] = "跳过出牌阶段",
  ["@@lingling__zhaqiao-turn"] = "跳过出牌阶段",
  ["#lingling__yexi-invoke"] = "夜袭：是否进行三次判定？若为黑色此【杀】获得额外效果，若为红色 %dest 摸一张牌",
}

return extension
